package com.ququ.syb.mqhandler.redis;

import com.alibaba.fastjson.JSONObject;
import com.ququ.syb.common.constant.RedisKeyConstant;
import com.ququ.syb.common.pojo.PayChannel;
import com.ququ.syb.common.pojo.PayOrder;
import com.ququ.syb.mqhandler.fegin.ChannelsRouterFegin;
import com.ququ.syb.mqhandler.fegin.PayChannelFegin;
import com.ququ.syb.mqhandler.fegin.PayOrderFegin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;

@Component
public class RedisExpiredListener implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(RedisExpiredListener.class);

    @Autowired
    private PayOrderFegin payOrderFegin;
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private ChannelsRouterFegin channelsRouterFegin;
    @Autowired
    private RedisDao redisDao;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onMessage(Message message, byte[] bytes) {
        Jedis jedis = redisDao.getJedis();
        try {
            String expiredKey = message.toString();
//            logger.debug("收到Redis队列消息:{}", expiredKey);
            if (expiredKey.startsWith(RedisKeyConstant.PAYORDER_TIMEOUT)) {
                //如果是Order:开头的key，进行处理
                String tradenum = expiredKey.replace(RedisKeyConstant.PAYORDER_TIMEOUT, "");
                if (jedis.sismember(RedisKeyConstant.PAYORDER_TIMEOUT_SET,tradenum)) {
                    jedis.srem(RedisKeyConstant.PAYORDER_TIMEOUT_SET,tradenum);
                    logger.debug("支付订单:{} 已经超时过期，正在进行超时处理", tradenum);
                    PayOrder payOrder = payOrderFegin.getPayOrder(tradenum).getData();
                    PayChannel payChannel = payChannelFegin.getPayChannel(payOrder.getPaychannelid()).getData();
                    if (payChannel.getOrdercloseable() == null || payChannel.getOrdercloseable() == 0){
                        logger.debug("{}订单通道不支持关闭功能",tradenum);
                        return;
                    }
                    JSONObject extParams = new JSONObject();
                    extParams.put("paytime",simpleDateFormat.format(payOrder.getPaytime()));
                    channelsRouterFegin.close(payOrder.getPayeeaccount(),payOrder.getPaychannelid(),tradenum,payOrder.getAmount(),extParams.toJSONString());
                }else
                    logger.debug("超时支付订单{}已经被其他生意宝进程处理，不再重复处理",tradenum);
            }
        }catch (Exception e){
            logger.error("订单超时处理异常",e);
        }finally {
            redisDao.close(jedis);
        }
    }
}
